package com.chuangzhi.controller;

import com.chuangzhi.entity.Account;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AccountController {

    @GetMapping("/{url}")
    public String redirect(@PathVariable("url")String url){
        return url;

    }

    @PostMapping("/login")
    public String login(String username, String password, Model model){
        //拿到subject
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        //拿到用户名交给shiro去做
        //捕获异常
        try{
            subject.login(token);
            //因为认证中用户信息已保存 所以直接获取 getPrincipal
            Account account = (Account) subject.getPrincipal();
            subject.getSession().setAttribute("account",account);
            return "index";
        }catch (UnknownAccountException e){
            //用户名不存在抛出 UnknownAccountException 异常 返回信息
            model.addAttribute("msg","用户名错误！");
            e.printStackTrace();
            return "login";
        }catch (IncorrectCredentialsException e){
            //非法密码 抛出 IncorrectCredentialsException 异常
            model.addAttribute("msg","密码错误！");

            e.printStackTrace();
            return "login";

        }
       // debug 接着跳转到 realm  AuthenticationInfo 对 账号密码进行判断
    }
    @GetMapping("/unauth")
    @ResponseBody
    public String unauth() {
        return "未授权，无法访问！";
    }

    @GetMapping("/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        //销毁
        subject.logout();
        return "login";

    }
}
